<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class BaseModel extends Model
{
  use HasFactory;

  protected $guarded = ['id'];

  protected function serializeDate($date)
  {
    return $date->format('Y-m-d H:i');
  }

  public function scopePage($q, $size = 10)
  {
    return $q->paginate(request()->input('page_size', $size));
  }

  public function scopeToday($q)
  {
    return $q->whereDate('updated_at', today()->format('Y-m-d'));
  }

  public function scopeThisMonth($q)
  {
    return $q->whereYear('updated_at', now()->format('Y'))->whereMonth('updated_at', now()->format('m'));
  }

  public function scopeWithSumBetween($q, $relation, $field, $range, $date_filed)
  {
    $snake = \Str::snake($relation);
    $q->withCount(["{$relation} as {$snake}_sum_{$field}" => function ($query) use ($date_filed, $field, $range) {
      $query->whereBetween($date_filed, $range)->select(\DB::raw("sum({$field})"));
    }]);
  }

  public function scopeWithCountBetween($q, $relations, $range, $date_filed)
  {
    $relations = \Arr::wrap($relations);
    // dump($relations);
    foreach ($relations as $relation) {
      $snake = \Str::snake($relation);
      $q->withCount(["{$relation} as {$snake}_count" => function ($query) use ($date_filed, $range) {
        $query->whereBetween($date_filed, $range);
      }]);
    }
  }
}
